package com.core.ui.customtag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.core.protocols.ICustomDatasourceDelegate;
import com.core.protocols.IMenuDatasource;
import com.core.protocols.IMenuDelegate;
import com.core.ui.customview.MenuItemCell;

public class PageMenuView
        extends TagSupport
        implements ICustomDatasourceDelegate {

	private static final long serialVersionUID = 1L;
	private IMenuDatasource   datasource;



	public IMenuDatasource getDatasource () {

		return datasource;
	}



	public void setDatasource ( IMenuDatasource datasource ) {

		this.datasource = datasource;
		if ( this.datasource != null ) {
			this.datasource.setCustomDatasourceDelegate(this);
		}
	}

	private IMenuDelegate delegate;



	public IMenuDelegate getDelegate () {

		return delegate;
	}



	public void setDelegate ( IMenuDelegate delegate ) {

		this.delegate = delegate;
	}



	public PageMenuView() {

		datasource = null;
		delegate = null;
	}



	public void release () {

		super.release();
		datasource = null;
		delegate = null;
	}



	public int doStartTag ()
	        throws JspException {

		if ( datasource == null ) {
			return SKIP_BODY;
		}

		datasource.reloadData();

		return SKIP_BODY;
	}



	@Override
	public void refreshContent () {

		StringBuilder sb = new StringBuilder();

		sb.append("<div class=\"header_menu\"><div class=\"header_menu_navigator\">");

		int numberOfItems = datasource.numberOfItems();
		for ( int i = 0; i < numberOfItems; i++ ) {
			MenuItemCell itemCell = datasource.itemAtIndex(i);
			if ( itemCell != null ) {
				sb.append(itemCell.toString());
			}
		}

		sb.append("</div></div>");

		try {
			JspWriter writer = pageContext.getOut();
			writer.append(sb.toString());
		} catch ( IOException e ) {
			// throw new JspException(e.getMessage());
		}

	}

}
